package com.yc.web;

import com.yc.bean.Account;
import com.yc.biz.AccountBiz;
import com.yc.biz.BizException;
import com.yc.web.bean.Result;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;

@RestController
public class IndexAction {

    @Resource
    private AccountBiz abiz;

    @RequestMapping("find")
    public Account findById(int id) {
        return abiz.find(id);
    }

    @RequestMapping("withdraw.do")
    public Result withdraw(@Valid Account acc, Errors errors) {
        if(errors.hasErrors()){
            return new Result(0, "提交数据错误", errors.getAllErrors());
        }
        try{
            Account dbacc = abiz.withdraw(acc.getAccountid(), acc.getBalance());
            return new Result(1, "存款成功", dbacc);
        } catch (BizException e){
            e.printStackTrace();
            errors.rejectValue((String) e.getData(), "0001", e.getMessage());
            return new Result(0, "提交数据错误", errors.getAllErrors());
        }
    }

    @RequestMapping("reg.do")
    public Result register(@Valid Account acc, Errors errors) {
        if(errors.hasErrors()){
            return new Result(0, "提交数据错误", errors.getAllErrors());
        }
        try{
           abiz.register(acc);
            return new Result(1, "注册成功", null);
        } catch (BizException e){
            e.printStackTrace();
            errors.rejectValue((String) e.getData(), "0002", e.getMessage());
            return new Result(0, "提交数据错误", errors.getAllErrors());
        }
    }


}
